//  存放路由处理函数模块, 为了保证路由模块的纯粹性
const path = require('path')
const sqlPath = path.join(__dirname, 'sql/index')
const { isRegisterSql, addRegisterSql, checkLoginSql } = require(sqlPath)
const { genPassword } = require('../utils/secret')
/**
 * 注册实现步骤
 *  1. 检测表单数据是否合法
 *  2. 检测用户名是否被占用
 *  3. 对密码进行加密
 *  4. 插入到数据库中
 */
regUser = async (req, res) => {
    const { username, password } = req.body
    // 检测用户名是否被占用
    let isRegisterRes = await isRegisterSql(username)
    if (isRegisterRes.code === 0) {
        return res.send(isRegisterRes.message)
    } else {
        let addRegisterRes = await addRegisterSql({ username, password: genPassword(password), nickname: username, email: 'test' })
        return res.send(addRegisterRes)
    }
}

login = async (req, res) => {
    const { username, password } = req.body
    let checkLoginRes = await checkLoginSql(username, password)
    res.send(checkLoginRes)
}

module.exports = {
    regUser,
    login
}